<?php
namespace Web\Controller;
use Think\Controller;
use Web\Logic\RoleLogic;
use Web\Logic\CommonLogic;
class DepartmentController extends BaseController {

    public function index(){
        $arr = M('m_department')->where(array('is_show'=>1))->field('id,name as name,parent_id as pid')->order('id asc')->select();
        $list = array_map(function($v){return array('id'=>$v['id'], 'name'=>$v['name'], 'pId'=>$v['pid']);}, $arr);
        $this->assign('list', json_encode($list));
        $this->display();
    }


    public function department_lists(){
        $name = $_REQUEST['name'];

        if(!empty($name)){
          $map['m.name'] = array('like', "%{$name}%");
        }

        $count = M('m_department')->alias('m')->where($map)->count();

        $Page  = $this->getpage($count,30);
        $Page->parameter['name']   =   urlencode($name);

        $lists = M('m_department')
            ->alias('m')
            ->join('LEFT JOIN '.C('DB_PREFIX').'member mem ON mem.userid =m.user_id')
            ->join('LEFT JOIN '.C('DB_PREFIX').'m_department mp ON m.parent_id =mp.id')
            ->field("m.*,mem.username,mp.name as pname")
            ->limit($Page->firstRow.','.$Page->listRows)
            ->order('m.id asc')
            ->where($map)
            ->select();

        $this->assign("list",$lists);
        $show  = $this->bootstrap_page_style($Page->show());
        $this->assign('empty','<td colspan="4">没有数据</td>');
        $this->assign('page',$show);
        $this->display();

    }

        /**
     * @desc 添加用户
     * @param rolename 用户名
     * @param notes 备注
     */
    public function department_add()
    {
		if(IS_POST){
			$rules = array(
				array('name','require','部门名称必填！'), //默认情况下用正则进行验证
				array('name','','部门名称已经存在！',0,'unique',1),
				array('parent_id','require','上级部门必选！'),
			);

			$Department = M('m_department');
			if (!$Department->validate($rules)->create()){
				 exit('<script>parent.notify("' . $Department->getError() . '");</script>');
			} else {
				$Department->user_id = session(C('SESSION_ADMIN_ID'));
				$Department->created_time = date('Y-m-d H:i:s');
				$Department->updated_time = date('Y-m-d H:i:s');
				$ins = $Department->add();
				if($ins){
					$cpnids = I('cpn_ids');
					if($cpnids){
						$cpn_ids = explode(',', $cpnids);
						$data = array_map(function($v) use($ins){return array('department_id'=>$ins, 'cpn_id'=>$v);}, $cpn_ids);
						M('day_department_cpn')->addAll($data);
					}
					//保存选择的时间表变量
					$varid = I('varid');
					$data = array_map(function($v) use($ins){return array('department_id'=>$ins, 'table_config_id'=>$v);}, $varid);
					M('day_department_timetable')->addAll($data);
					exit('<script>parent.location="'.U('department_lists').'";</script>');
				} else {
					exit('<script>parent.notify("保存失败！");</script>');
				}
			}
		} else {
			$varlist = M('day_table_config')->alias('c')
				->join('LEFT JOIN '.C('DB_PREFIX').'devices_class d ON c.class_id=d.class_id')
				->field('c.id,c.show_name,d.class_name')
				->order('c.class_id,c.control_var')
				->select();
			$this->assign('varlist', $varlist);

			//调用模板
			$this->assign('user_list', $this->getUserList());
			//调用模板
			$this->display();
		}
    }

    /**
     * @desc 用户修改
     * @param roleid 用户id
     */
    public function department_edit()
    {
        //接受 用户id
        $id = I('id/d', 0);

		if(IS_POST){
			$rules = array(
				array('name','require','部门名称必填！'), //默认情况下用正则进行验证
				array('name','','部门名称已经存在！',0,'unique',2),
				array('parent_id','require','上级部门必选！'),
			);
			$Department = M('m_department');
			$Department_timetable = M('day_department_timetable');
			if (!$Department->validate($rules)->create()){
				exit('<script>parent.notify("' . $Department->getError() . '");</script>');
			} else {
				$Department->user_id = session(C('SESSION_ADMIN_ID'));
				$Department->updated_time = date('Y-m-d H:i:s');
				$res = $Department->save();
				if($res !== false){
					M('day_department_cpn')->where(array('department_id'=>$id))->delete();
					$cpnids = I('cpn_ids');
					if($cpnids){
						$cpn_ids = explode(',', $cpnids);
						$data = array_map(function($v) use($id){return array('department_id'=>$id, 'cpn_id'=>$v);}, $cpn_ids);
						M('day_department_cpn')->addAll($data);
					}
					//保存选择的时间表变量
					$varid = I('varid');
					$data = array_map(function($v) use($id){return array('department_id'=>$id, 'table_config_id'=>$v);}, $varid);
					$Department_timetable->where(array('department_id'=>$id))->delete();
					$Department_timetable->addAll($data);

					//清理时间表日模板变量字段
					$map1['id'] = array('not in', $varid);
					$field_names = M('day_table_config')->where($map1)->getField('field_name', true);
					$tids = M('day_tplname')->where(array('department_id'=>$id))->getField('tid', true);
                    if($tids){
					    $map['tid'] = array('in', $tids);

					    $dat = array();
					    foreach($field_names as $vv){
						    $dat[$vv] = null;
					    }

					    M('day_template')->where($map)->save($dat);
                    }
					exit('<script>parent.location="'.U('department_lists').'";</script>');
				} else {
					exit('<script>parent.notify("保存失败！");</script>');
				}
			}
		} else {
			//查询信息
			$datalist = M('m_department')->alias('m')
				->join('LEFT JOIN '.C('DB_PREFIX').'m_department mp ON m.parent_id =mp.id')
				->field('m.*,mp.name as pname')
				->where(array('m.id'=>$id))->find();

			$cpn_ids = M('day_department_cpn')->where(array('department_id'=>$id))->getField('cpn_id', true);
			$cpn_ids = array_map(function($v){return "'{$v}'";}, $cpn_ids);
			$this->assign('cpn_ids', implode(',', $cpn_ids));
			$this->assign('datalist',$datalist);

			$varlist = M('day_table_config')->alias('c')
				->join('LEFT JOIN '.C('DB_PREFIX').'day_department_timetable t ON c.id=t.table_config_id AND t.department_id='.$id)
				->join('LEFT JOIN '.C('DB_PREFIX').'devices_class d ON c.class_id=d.class_id')
				->field('c.id,c.show_name,t.department_id as tid,d.class_name')
				->order('c.class_id,c.control_var')
				->select();

			$this->assign('varlist', $varlist);

			//调用模板
			$this->assign('user_list', $this->getUserList());

			$this->display();
		}
    }

	/**
     * @desc 用户删除
     * @param roleid 用户id
     */
    public function department_deletes()
    {
        //接受 roleid
        $id = $_REQUEST['id'];
        $r = M('m_department')->where(array('id'=>$id))->delete();
        if($r)
        {
            $this->redirect('department_lists');
        }
    }

	public function checkVars(){
		$department_id = I('id');
		$varid = I('varid/a');

		$old_table_config_ids = M('day_department_timetable')->where(array('department_id'=>$department_id))->getField('table_config_id', true);

		$no_exist_varid = array_diff($old_table_config_ids, $varid);

		if($no_exist_varid){
			$map['id'] = array('in', $no_exist_varid);
			$class_ids = M('day_table_config')->where($map)->distinct(true)->getField('class_id', true);

			if($class_ids){
				$map1['t.department_id'] = $department_id;
				$map1['t.device_class'] = array('in', $class_ids);
				$list = M('day_tplname')->alias('t')
					->join(C('DB_PREFIX').'day_template e ON t.tid=e.tid')
					->where($map1)
					->field('t.tid,t.title')
					->distinct(true)
					->select();
				$tplnames = array_column($list, 'title');
				if($tplnames){
					$this->ajaxReturn(array('msg'=>'1', 'content'=>'时间表变量的改变会影响此部门以下日模板设置：<br>'.implode(', ', $tplnames)));
					exit;
				}
			}
		}

		$this->ajaxReturn(array('msg'=>'0'));
	}


     public function task_lists(){
        $name = $_REQUEST['name'];

        if(!empty($name)) $map['name'] = array('like', "%{$name}%");

        $count = M('m_task')->where($map)->count();

        $Page  = $this->getpage($count,30);
        $Page->parameter['name']   =   urlencode($name);

        $lists = M('m_task')
            ->alias('m')
            ->join('LEFT JOIN '.C('DB_PREFIX').'member mem ON mem.userid =m.user_id')
            ->field("m.*,mem.username")
            ->limit($Page->firstRow.','.$Page->listRows)
            ->order('m.id asc')
            ->where($map)
            ->select();

        $this->assign("list",$lists);
        $show  = $this->bootstrap_page_style($Page->show());
        $this->assign('empty','<td colspan="4">没有数据</td>');
        $this->assign('page',$show);
         $this->assign('name',$name);
        $this->display();

    }

        /**
     * @desc 添加用户
     * @param rolename 用户名
     * @param notes 备注
     */
    public function task_add()
    {
        //实例化 logic
        //获取提交隐含域
        $subs = $_REQUEST['sub'];
        //接受用户名
        $data = $_REQUEST['data'];
        if($data)
        {
           $data['is_show'] = 1;
           $data['user_id'] = session(C('SESSION_ADMIN_ID'));
           $r = M('m_task')->add($data);
           $this->redirect('task_lists');
        }else{
        //调用模板
        $this->display();
        }
    }

    /**
     * @desc 用户删除
     * @param roleid 用户id
     */
    public function task_deletes()
    {
        //接受 roleid
        $id = $_REQUEST['id'];
        $r = M('m_task')->where(array('id'=>$id))->delete();
        if($r)
        {
            $this->redirect('task_lists');
        }
    }

    /**
     * @desc 用户修改
     * @param roleid 用户id
     */
    public function task_edit()
    {
        //接受 用户id
        $id = $_REQUEST['id'];

        //接受表单提交
        $sub = $_REQUEST['sub'];
        //接受修改信息
        $data = $_REQUEST['data'];
        if($data && $sub)
        {
           $data['user_id'] = session(C('SESSION_ADMIN_ID'));
           $r = M('m_task')->where(array('id'=>$id))->save($data);
           $this->redirect('task_lists');

        } else{


            //查询信息
            $datalist = M('m_task')->where(array('id'=>$id))->find();

            $this->assign('datalist',$datalist);
            $this->display();
        }
    }


     public function device_lists(){
        $name = $_REQUEST['name'];

        if(!empty($name)) $map['name'] = array('like', "%{$name}%");

        $count = M('m_device')->where($map)->count();

        $Page  = $this->getpage($count,30);
        $Page->parameter['name']   =   urlencode($name);

        $lists = M('m_device')
            ->alias('m')
            ->join('LEFT JOIN '.C('DB_PREFIX').'member mem ON mem.userid =m.user_id')
            ->join('LEFT JOIN '.C('DB_PREFIX').'m_department mp ON m.department_id =mp.id')
            ->field("m.*,mem.username,mp.name as department_name")
            ->limit($Page->firstRow.','.$Page->listRows)
            ->order('m.id asc')
            ->where($map)
            ->select();





        $this->assign("list",$lists);
        $show  = $this->bootstrap_page_style($Page->show());
        $this->assign('empty','<td colspan="4">没有数据</td>');
        $this->assign('page',$show);
         $this->assign('name',$name);
        $this->display();

    }
    function getDeviceList($id){
          $map['department_id'] = $id;
          $map['is_show'] = 1;
          $lists = M('m_device')
            ->alias('m')
            ->field("m.*")
            ->where($map)
            ->select();
         $list =  json_encode($lists);
        echo  $list;
    }

        /**
     * @desc 添加用户
     * @param rolename 用户名
     * @param notes 备注
     */
    public function device_add()
    {
        //实例化 logic
        //获取提交隐含域
        $subs = $_REQUEST['sub'];
        //接受用户名
        $data = $_REQUEST['data'];
        if($data)
        {
           $data['is_show'] = 1;
           $data['user_id'] = session(C('SESSION_ADMIN_ID'));
           $r = M('m_device')->add($data);
           $this->redirect('device_lists');
        }else{
        //调用模板
        $this->display();
        }
    }

    /**
     * @desc 用户删除
     * @param roleid 用户id
     */
    public function device_deletes()
    {
        //接受 roleid
        $id = $_REQUEST['id'];
        $r = M('m_device')->where(array('id'=>$id))->delete();
        if($r)
        {
            $this->redirect('device_lists');
        }
    }

    /**
     * @desc 用户修改
     * @param roleid 用户id
     */
    public function device_edit()
    {
        //接受 用户id
        $id = $_REQUEST['id'];

        //接受表单提交
        $sub = $_REQUEST['sub'];
        //接受修改信息
        $data = $_REQUEST['data'];
        if($data && $sub)
        {
           $data['user_id'] = session(C('SESSION_ADMIN_ID'));
           $r = M('m_device')->where(array('id'=>$id))->save($data);
           $this->redirect('device_lists');

        } else{

            //查询信息
            $datalist = M('m_device')->alias('d')
             ->join('LEFT JOIN '.C('DB_PREFIX').'m_department mp ON d.department_id =mp.id')
             ->field('d.*,mp.name as department_name')
            ->where(array('d.id'=>$id))->find();
            $this->assign('datalist',$datalist);
            $this->display();
        }
    }
     public function getDepartmentSelect(){
        $list = $this->getBaseDepartmentForSelect();
		$this->ajaxReturn($list);
    }

    public function getDepartment(){
        $arr = M('m_department')->where(array('is_show'=>1))->field('id,name as name,parent_id as pid')->order('name asc')->select();
        $list = array_map(function($v){return array('id'=>$v['id'], 'name'=>$v['name'], 'pId'=>$v['pid'], 'open'=>true);}, $arr);
		$this->ajaxReturn($list);
    }

	//ADD CPN
	public function addcpn(){
		$keyword = trim(I('keyword',''));
		$cpn_class = I('cpn_class','');

		if(!empty($cpn_class)) $map['cpn_type'] = $cpn_class;
		if(!empty($keyword)) $map['show_name'] = array('like',"%{$keyword}%");

		$list = M('cpn')
			->where($map)
			->field('id,show_name')
			->order('cpn_name asc')
			->select();

		$classList = M('devices_class')->where(array('is_show'=>1))->getField('class_id,class_name');

		$this->assign('classList', $classList);
		$this->assign('list', $list);
		$this->display();
	}

	public function cpns(){
		$keyword = trim(I('keyword',''));
		$cpn_class = I('cpn_class','');
		$sum_id = I('sum_id');
		$group_id = I('group_id');

		if(!empty($cpn_class)) $map['cpn_type'] = $cpn_class;
		if(!empty($keyword)) $map['show_name'] = array('like',"%{$keyword}%");

		$list = M('cpn')
			->where($map)
			->field('id,show_name')
			->order('cpn_name asc')
			->select();

		$i = 0;
		$html = '<tr>';
		foreach($list as $v) {
			$mod = ($i % 5 );
			++$i;
			$checked = is_null($v['lid']) ? '' : 'checked';
			$html .= '<td><label><input class="cpnchk" type="checkbox" name="id[]" value="'.$v["id"].'"'.$checked.' />'.$v["show_name"].'</label></td>';
			if($mod  ==  4) $html .= '</tr><tr>';
		}
		$html .= '</tr>';
		echo $html;
	}

	public function clearCpn(){
		if(IS_POST){
			$department_id = I('id',0);
			M('day_department_cpn')->where(array('department_id'=>$department_id))->delete();
			echo '1';
		}
	}


}